package com.lining.orangeservice.mapper;

import com.lining.orangeservice.entity.po.Permission;
import com.lining.orangeservice.entity.po.Role;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface RoleMapper {

    /**
     * 根据用户ID查询角色列表
     */
    @Select("SELECT r.id, r.role_name, r.role_code, r.description, r.status, " +
            "r.create_time, r.update_time, r.deleted " +
            "FROM sys_role r " +
            "INNER JOIN sys_user_role ur ON r.id = ur.role_id " +
            "WHERE ur.user_id = #{userId} AND r.status = 1 AND r.deleted = 0")
    @Results({
        @Result(property = "id", column = "id"),
        @Result(property = "roleName", column = "role_name"),
        @Result(property = "roleCode", column = "role_code"),
        @Result(property = "description", column = "description"),
        @Result(property = "status", column = "status"),
        @Result(property = "createTime", column = "create_time"),
        @Result(property = "updateTime", column = "update_time"),
        @Result(property = "deleted", column = "deleted")
    })
    List<Role> selectRolesByUserId(@Param("userId") Long userId);

    /**
     * 根据角色ID查询权限列表
     */
    @Select("SELECT p.id, p.perm_name, p.perm_code, p.perm_type, p.parent_id, " +
            "p.path, p.component, p.icon, p.sort, p.status, p.create_time, p.update_time " +
            "FROM sys_permission p " +
            "INNER JOIN sys_role_permission rp ON p.id = rp.permission_id " +
            "WHERE rp.role_id = #{roleId} AND p.status = 1")
    List<Permission> selectPermissionsByRoleId(@Param("roleId") Long roleId);

    /**
     * 根据ID查询角色
     */
    @Select("SELECT * FROM role WHERE id = #{id}")
    Role selectById(@Param("id") Long id);


    /**
     * 批量插入角色权限关系
     */
    @Insert({
            "<script>",
            "INSERT INTO role_permission (role_id, permission_id) VALUES ",
            "<foreach collection='permissionIds' item='permissionId' separator=','>",
            "(#{roleId}, #{permissionId})",
            "</foreach>",
            "</script>"
    })
    void insertRolePermissions(@Param("roleId") Long roleId, @Param("permissionIds") List<Long> permissionIds);

}